<?php
namespace App\Controllers\Order;
use App\Models\Goods\Goods;
use App\Models\Order\Order;
use App\Models\Coupons\Coupons;
use App\Models\Coupons\CouponsMy;

/**
*	取消订单
*/
class CancelOrder extends \App\Libs\Base\BaseAction
{
    protected function beforeRun() {
        parent::beforeRun();
        $this->needLogin = TRUE;
    }
	
	public function execute(){
		$user = $this->session->user;
		//获取信息
		$orderSn = $this->request->get('orderSn');//订单号
		
		//检测订单信息是否正确
		$orderInfo = Order::find(array(
			'order_sn = :orderSn: and uid = '.$user->id,
			'bind' => array( 'orderSn' => $orderSn )
		));
		if( empty( $orderInfo ) ){
			return \App\Libs\Views\Json::view(1, '未查到相关订单信息', Null );
		}
		
		//验证订单是否支付
		if( $orderInfo->status == 1 ){
			return \App\Libs\Views\Json::view(1, '订单已支付，请联系客服', Null );
		}
		
		//验证订单其他状态
		if( $orderInfo->status != 0 ){
			return \App\Libs\Views\Json::view(1, '订单状态有误，请联系客服', Null );	
		}
		
		//确定取消
		$orderInfo->status = 2;
		if( !empty( $orderInfo->ticket_id ) ){
			//恢复优惠券
			$couponsMyInfo = CouponsMy::find(array(
				'ticket_id=:ticket_id: and uid = '.$user->id,
				'bind' => array( 'ticket_id' => $orderInfo->ticket_id )
			));
			if( empty( $couponsMyInfo ) ){
				return \App\Libs\Views\Json::view(1, '未查到相关订单优惠券信息，请联系客服', Null );		
			}
			$couponsMyInfo->status = 0;
		}
		if( !empty( $orderInfo->gid ) ){
			//恢复商品库存
			$goodsInfo = Goods::find(array(
				'id = :goodsId:',
				'bind' => array( 'goodsId' => $orderInfo->gid )
			));
			if( empty( $goodsInfo ) ){
				return \App\Libs\Views\Json::view(1, '未查到相关订单商品信息，请联系客服', Null );		
			}
			$goodsInfo->goods_store += $orderInfo->sum;
		}
		$orderInfo->save();
		if( isset( $goodsInfo  ) ){
			$goodsInfo->save();
		}
		if( isset( $couponsMyInfo) ){
			$couponsMyInfo->save();
		}
		
		return \App\Libs\Views\Json::view(0, '取消订单成功', Null );
	}
}
